package com.ferret.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ferret.bean.entity.ReadPic;
import com.ferret.bean.entity.RyGzryxxcj;
import com.ferret.dao.ReadPicDao;
import com.ferret.dao.RyGzryxxcjDao;
import com.ferret.dao.specifications.ReadPicSpecification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class ReadPicService {
    @Resource
    private ReadPicDao readPicDao;
    @Resource
    private RyGzryxxcjDao ryGzryxxcjDao;
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final String PICTURES_DIRECTORY = System.getProperty("user.dir") + File.separator + "pic" + File.separator;
    private static final String PICTURES_DIRECTORY_ALL = System.getProperty("user.dir") + File.separator + "all_pic" + File.separator;

    @Value("${sysConfig.savePath}")
    private String savePath;

    /**
     * 查询所有在控人员图片
     */

    public void selectAllPic() {
        logger.info("-----------开始查询------------------");
        long countNum = readPicDao.findAllPagedByOracleCount();
        logger.info("----------查询总条数---------" + countNum);
        int pageNum = Math.toIntExact(countNum / 1000) + 1;
        Integer pageSize = 1000;
        // 获取当前日期用于创建目录
        String currentDate = java.time.LocalDate.now().toString();
        String dateDirectory = PICTURES_DIRECTORY_ALL + currentDate + File.separator;
        // 确保日期目录存在
        FileUtil.mkdir(dateDirectory);

        for (int i = 0; i < pageNum; i++) {
            List<ReadPic> readPicList = this.queryPageRecords(i, pageSize);
            readPicList.forEach(readPic -> {
                String djdw = readPic.getDjdw();
                String glgzrybh = readPic.getGlgzrybh();
                String ryzt = readPic.getRyzt();
                String gmsfhm = readPic.getGmsfhm();
                String fileName = StrFormatter.format("{}.{}", gmsfhm, ImgUtil.IMAGE_TYPE_JPG);
                // 保存到日期子目录下
                String savePath = StrUtil.join(StrPool.SLASH, dateDirectory, fileName);
                logger.info("----------开始保存---------" + savePath);
                try {
                    FileUtil.writeBytes(readPic.getZp(), savePath);
                } catch (Exception e) {
                    logger.info("----------保存失败---------" + savePath);
                }
            });
        }
        logger.info("-----------处理完成------------------");
    }

    public List<ReadPic> queryPageRecords(Integer pageNum, Integer pageSize) {
        int startRowIndex = pageNum * pageSize + 1; // Oracle的ROWNUM是从1开始的
        int endRowIndex = (pageNum + 1) * pageSize;
        List<ReadPic> searchRecordsPage = readPicDao.findAllPagedByOracle(startRowIndex, endRowIndex);
        return searchRecordsPage;
    }

    /**
     * 按区域代码查询
     *
     * @param areaCodes
     * @param ryztStatus
     */

    public void selectConditionPicByAreaCodes(List<String> areaCodes, String ryztStatus, LocalDateTime startTime, LocalDateTime endTime) {
        logger.info("-----------开始按区域代码查询------------------");
        // 构建查询条件
        Specification<ReadPic> spec = Specification.where(ReadPicSpecification.withStatus(ryztStatus).and(ReadPicSpecification.withTimeRange(startTime, endTime)));

        // 只有当areaCodes不为空时才添加区域代码条件
        if (CollUtil.isNotEmpty(areaCodes)) {
            spec = spec.and(ReadPicSpecification.withAreaCodes(areaCodes));
        }
        // 获取符合条件的总记录数
        long countNum = readPicDao.count(spec);
        logger.info("----------查询总条数---------" + countNum);

        // 计算分页数量
        int pageNum = Math.toIntExact(countNum / 1000) + 1;
        Integer pageSize = 1000;

        // 获取当前日期用于创建目录
        String currentDate = java.time.LocalDate.now().toString();
        String dateDirectory = PICTURES_DIRECTORY + currentDate + File.separator;

        // 确保日期目录存在
        FileUtil.mkdir(dateDirectory);

        // 分页查询并处理数据
        for (int i = 0; i < pageNum; i++) {
            Pageable pageable = PageRequest.of(i, pageSize);
            List<ReadPic> readPicList = readPicDao.findAll(spec, pageable).getContent();

            readPicList.forEach(readPic -> {
                String djdw = readPic.getDjdw();
                String glgzrybh = readPic.getGlgzrybh();
                String ryzt = readPic.getRyzt();
                String gmsfhm = readPic.getGmsfhm();
                if (StrUtil.isNotBlank(gmsfhm)) {
                    String fileName = StrFormatter.format("{}.{}", gmsfhm, ImgUtil.IMAGE_TYPE_JPG);
                    // 保存到日期子目录下
                    String savePath = StrUtil.join(StrPool.SLASH, dateDirectory, fileName);
                    logger.info("----------开始保存---------" + savePath);
                    try {
                        FileUtil.writeBytes(readPic.getZp(), savePath);
                    } catch (Exception e) {
                        logger.info("----------保存失败---------" + savePath);
                    }
                }
            });
        }
        logger.info("-----------按区域代码查询处理完成------------------");
    }


    public void getAllZkRy() {
        List<RyGzryxxcj> searchAllData = ryGzryxxcjDao.findAllByZkry();
        JSONObject jsonObject = JSONUtil.createObj();
        jsonObject.set("data", searchAllData);
        logger.info("----------查询结果----" + jsonObject);
        FileUtil.writeString(jsonObject.toString(), savePath + File.separator + "zkry.json", "UTF-8");
    }

    public void selectAllPic1() {
        logger.info("-----------开始查询------------------");
        List<ReadPic> searchRecordsPage = readPicDao.findTestDataList();
        List<JSONObject> jsonList = new ArrayList<>();
        if (CollUtil.isNotEmpty(searchRecordsPage)) {
            searchRecordsPage.forEach(readPic -> {
                JSONObject jsonObject = new JSONObject();
                String djdw_GLGZRYBH = StrFormatter.format("{}_{}", readPic.getDjdw(), readPic.getGlgzrybh());
                jsonObject.set("djdw_GLGZRYBH", djdw_GLGZRYBH);
                jsonList.add(jsonObject);
            });
        }
        logger.info("----------查询结果----" + jsonList);
        Long searchRecordsCount = readPicDao.findTestDataCount();
        logger.info("----------查询总条数---------" + searchRecordsCount);
        Long findAllPagedByOracleCount = readPicDao.findAllPagedByOracleCount();
        logger.info("----------查询关注人员总条数---------" + findAllPagedByOracleCount);
        logger.info("-----------处理完成------------------");
    }

}
